package com.angel.service;

import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;

import com.angel.entity.Task;
import com.angel.port.IActivity;
import com.angel.util.HttpUtil;
import com.angel.util.UserInfoUtil;

import android.R;
import android.app.Activity;
import android.app.Service;
import android.content.Intent;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.util.Log;

public class TaskService extends Service implements Runnable {
	private static Queue<Task> tasks = new LinkedList<Task>();// 任务队列
	private static List<Activity> lists = new ArrayList<Activity>();// activity线性表

	private MyHandler handler = new MyHandler();
	public static boolean isRun;// 标志线程是否继续运行
	private IActivity iActivity, iActivi;//

	private String actiContent;// 网络上获取的json
	private HashMap<String, String> map = new HashMap<String, String>();

	/* 处理返回结果 */
	class MyHandler extends Handler {
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case Task.LOGIN_ACTIVITY:
				iActivity = (IActivity) getActivityByName("LoginActivity");//
				iActivity.refresh(msg.obj);// 返回加载结果
				break;
			case Task.MAIN_ACITITY:
				iActivity = (IActivity) getActivityByName("MainActivity");//
				iActivity.refresh(msg.obj);// 返回加载结果
				break;
			case Task.DETAIL_ACTIVITY:
				iActivity = (IActivity) getActivityByName("ActivityDetail");//
				iActivity.refresh(msg.obj);// 返回加载结果
				break;
			case Task.WILL_ACTIVITY:
				iActivity = (IActivity) getActivityByName("WilingMenuActivity");//
				iActivity.refresh(msg.obj);// 返回加载结果
				break;
			case Task.EDIT_WILL_ACTIVITY:
				iActivity = (IActivity) getActivityByName("WillingMenuEdit");//
				iActivity.refresh(msg.obj);// 返回加载结果");//
				iActivi = (IActivity) getActivityByName("WilingMenuActivity");
				iActivi.refresh(msg.obj);
				break;
			case Task.MY_ACTIVITY:
				iActivity = (IActivity) getActivityByName("MyActivity");//
				iActivity.refresh(msg.obj);// 返回加载结果";
				break;
			case Task.SEARCH_ACTIVITY:
				iActivity = (IActivity) getActivityByName("SearchActivity");//
				iActivity.refresh(msg.obj);// 返回加载结果");
				break;
			case Task.FEEKBACK_ACTIVITY:
				iActivity = (IActivity) getActivityByName("FeekBack");//
				iActivity.refresh(msg.obj);// 返回加载结果");
				break;
			case Task.REGISTER:
				iActivity = (IActivity) getActivityByName("Register2Activity");//
				iActivity.refresh(msg.obj);// 返回加载结果");
				break;
			case Task.QQBIND:
				iActivity = (IActivity) getActivityByName("QQBinding");//
				iActivity.refresh(msg.obj);// 返回加载结果");
				break;
			case Task.WEIBOBIND:
				iActivity = (IActivity) getActivityByName("SinaWeibo");//
				iActivity.refresh(msg.obj);// 返回加载结果");
				break;
			case Task.PHONEBIND:
				iActivity = (IActivity) getActivityByName("PhoneBinding");//
				iActivity.refresh(msg.obj);// 返回加载结果");
				break;
			case Task.EMAILBIND:
				iActivity = (IActivity) getActivityByName("EmailBinding");//
				iActivity.refresh(msg.obj);// 返回加载结果");
				break;
			case Task.CHANGESETTING:
				iActivity = (IActivity) getActivityByName("SetUpActivity");//
				iActivity.refresh(msg.obj);// 返回加载结果");
				break;
			case Task.GETREMINDTIME:
				iActivity = (IActivity) getActivityByName("MyActivity");//
				iActivity.refresh(msg.obj);// 返回加载结果");
			case Task.UPDATEREMINDTIME:
				iActivity = (IActivity) getActivityByName("SetUpActivity");//
				iActivity.refresh(msg.obj);// 返回加载结果");
				break;
			}
		}
	}

	/* 启动线程执行任务 */
	public void run() {
		while (isRun) {
			// Log.i("task","TaskService"+tasks.size());
			if (tasks.size() > 0)
				doTask();
		}
	}

	@Override
	public void onCreate() {
		super.onCreate();
		Thread thread = new Thread(this);
		thread.start();// 启动线程
		isRun = true;// 是否运行
	}

	/* 获取当前activity对象 */
	public Activity getActivityByName(String name) {
		// 遍历线性表lists
		if (!lists.isEmpty()) {
			for (Activity activity : lists) {
				if (-1 != activity.getClass().getName().toString()
						.indexOf(name)) {
					Log.i("activity", "activity count"
							+ activity.getClass().getName());
					return activity;
				}
			}
		}
		return null;
	}

	/* 添加activity到数组lists中 */
	public static void addActivity(Activity activity) {
		lists.add(activity);// 添加Activity
		Log.i("TaskService", "activity size:" + lists.size() + "activity name"
				+ activity.toString());
	}

	// 判断Activity是否存在
	public static void removeActivity(Activity activity) {
		lists.remove(activity);
		Log.i("TaskService", "activity size remove:" + lists.size()
				+ "activity name" + activity.toString());
	}

	// 新建任务
	public static void newTask(Task t) {
		addTask(t);
	}

	/* 将任务添加到队列中 */
	public static void addTask(Task t) {
		tasks.add(t);// 添加任务
	}

	// 执行具体任务
	public void doTask() {
		Task task = null;
		if (!tasks.isEmpty()) {
			task = tasks.poll();
			Message msg = new Message();
			msg.what = task.getTaskId();//

			// 判断任务ID，决定执行哪个任务
			switch (task.getTaskId()) {
			case Task.LOGIN_ACTIVITY:// 登陆任务
				try {
					map = task.getTaskParams();
					actiContent = HttpUtil.httpPost(HttpUtil.baseUrl + "login",
							map);
				} catch (UnsupportedEncodingException e2) {
					e2.printStackTrace();
				}
				msg.obj = actiContent;
				break;
			case Task.MAIN_ACITITY:// 主推活动
				map = task.getTaskParams();
				Log.i("TaskService", "userId:" + map.get("userId"));
				// 判断是登陆接口请求还是主推活动请求
				actiContent = HttpUtil.httpGet(HttpUtil.baseUrl
						+ "activityKind?userId=" + map.get("userId")
						+ "&activityKindId=" + map.get("activitiyKindId"));
				// actiContent=HttpUtil.httpPost(HttpUtil.baseUrl+"activityKind",
				// map);
				msg.obj = actiContent;
				break;
			case Task.DETAIL_ACTIVITY:// 活动详情
				try {
					map = task.getTaskParams();
					actiContent = HttpUtil.httpPost(HttpUtil.baseUrl
							+ "activity", map);
				} catch (UnsupportedEncodingException e1) {
					e1.printStackTrace();
				}
				msg.obj = actiContent;
				break;
			case Task.WILL_ACTIVITY:// 意愿清单
				map = task.getTaskParams();
				actiContent = HttpUtil.httpGet(HttpUtil.baseUrl
						+ "willList?userId=" + map.get("userId"));
				msg.obj = actiContent;
				break;
			case Task.EDIT_WILL_ACTIVITY:// 编辑意愿
				try {
					actiContent = HttpUtil.httpPost(HttpUtil.baseUrl
							+ "updateWill", task.getTaskParams());
				} catch (UnsupportedEncodingException e) {
					e.printStackTrace();
				}
				msg.obj = actiContent;
				break;
			case Task.MY_ACTIVITY:// 我的活动
				try {
					actiContent = HttpUtil.httpPost(HttpUtil.baseUrl
							+ "myActivity", task.getTaskParams());
				} catch (UnsupportedEncodingException e) {
					e.printStackTrace();
				}
				msg.obj = actiContent;
				break;
			case Task.SEARCH_ACTIVITY:// 搜索活动
				try {
					actiContent = HttpUtil.httpPost(HttpUtil.baseUrl
							+ "searchActivity", task.getTaskParams());
				} catch (UnsupportedEncodingException e) {
					e.printStackTrace();
				}
				msg.obj = actiContent;
				break;
			case Task.FEEKBACK_ACTIVITY:// 活动反馈
				try {
					actiContent = HttpUtil.httpPost(HttpUtil.baseUrl
							+ "opinion", task.getTaskParams());
				} catch (UnsupportedEncodingException e) {
					e.printStackTrace();
				}
				msg.obj = actiContent;
				break;
			case Task.REGISTER:// 注册
				map = task.getTaskParams();
				if (map.get("isBind").equals("1")
						|| map.get("isBind").equals("2")) {// 绑定手机,找回密码请求
					String bindUrl = HttpUtil.baseUrl + "updatePhone";
					try {
						actiContent = HttpUtil.httpPost(bindUrl, map);
					} catch (UnsupportedEncodingException e) {
						// TODO Auto-generated catch block
					}
					msg.obj = actiContent;
				} else {
					String registerUrl = HttpUtil.baseUrl + "register?"
							+ "telNum=" + map.get("telNum") + "&password="
							+ map.get("password");
					actiContent = HttpUtil.httpGet(registerUrl);
					msg.obj = actiContent;
				}

				break;
			case Task.QQBIND:// qq绑定
				try {
					actiContent = HttpUtil.httpPost(
							HttpUtil.baseUrl + "bindQq", task.getTaskParams());
				} catch (UnsupportedEncodingException e) {
					e.printStackTrace();
				}
				msg.obj = actiContent;
				break;
			case Task.WEIBOBIND:// 微博绑定
				try {
					actiContent = HttpUtil.httpPost(HttpUtil.baseUrl
							+ "bindWeibo", task.getTaskParams());
				} catch (UnsupportedEncodingException e) {
					e.printStackTrace();
				}
				msg.obj = actiContent;
				break;
			case Task.PHONEBIND:// 手机号绑定
				try {
					actiContent = HttpUtil.httpPost(HttpUtil.baseUrl
							+ "updatePhone", task.getTaskParams());
				} catch (UnsupportedEncodingException e) {
					e.printStackTrace();
				}
				msg.obj = actiContent;
				break;
			case Task.EMAILBIND:// 邮箱绑定
				try {
					actiContent = HttpUtil.httpPost(HttpUtil.baseUrl
							+ "bindEmail", task.getTaskParams());
				} catch (UnsupportedEncodingException e) {
					e.printStackTrace();
				}
				msg.obj = actiContent;
				break;
			case Task.CHANGESETTING:// 更改用户名
				map = task.getTaskParams();
				String userName = map.get("userName");
				if (userName != null) {
					try {
						actiContent = HttpUtil.httpPost(HttpUtil.baseUrl
								+ "updateUserName", task.getTaskParams());
					} catch (UnsupportedEncodingException e) {
						e.printStackTrace();
					}
				} else {

				}
				msg.obj = actiContent;
				break;
			case Task.GETREMINDTIME:// 获取提醒时间
				try {
					actiContent = HttpUtil.httpPost(HttpUtil.baseUrl
							+ "remindTime", task.getTaskParams());
				} catch (UnsupportedEncodingException e) {
					e.printStackTrace();
				}
				msg.obj = actiContent;
				break;
			case Task.UPDATEREMINDTIME:// 更新提醒时间
				try {
					actiContent = HttpUtil.httpPost(HttpUtil.baseUrl
							+ "remindTime", task.getTaskParams());
				} catch (UnsupportedEncodingException e) {
					e.printStackTrace();
				}
				msg.obj = actiContent;
				break;
			}
			handler.sendMessage(msg);// 发送
		}
	}

	@Override
	public IBinder onBind(Intent intent) {
		return null;
	}

	@Override
	public void onDestroy() {
		// TODO Auto-generated method stub
		isRun = false;
		super.onDestroy();
	}
}
